var express = require('express');
var router = express.Router();
var utils = require('../../functions/utils');

router.get('/' , function(req,res)
{
	var html = "<form name='tmpForm' method='post' action='/reportedCommentList'></form>";
	html +=	"<script language=javascript>tmpForm.submit();</script>";

	res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
	res.end(html);

});

function makeSelectYearString(year)
{
		var str  = '';
		for(var i = 2014 ; i <= 2030 ; i ++)
		{
			if(year == i)
				str += "<option value='" + i + "' SELECTED>"+i+"</option>";
			else
				str += "<option value='" + i + "'>"+i+"</option>";
		}

		return str;
};

function makeSelectMonthString(mon)
{
		var str  = '';
		for(var i = 1 ; i <= 12 ; i ++)
		{
			if(mon == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};

function makeSelectDayString(day)
{
		var str  = '';
		for(var i = 1 ; i <= 31 ; i ++)
		{
			if(day == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};

function makeSelectHourString(hour)
{
		var str  = '';
		for(var i = 0 ; i <= 23 ; i ++)
		{
			if(hour == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};

function makeSelectMinSecString(ms)
{
		var str  = '';
		for(var i = 0 ; i <= 59 ; i ++)
		{
			if(ms == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};




router.post('/', function(req,res)
{
	var sessionKey = req.session.key;

	if(utils.isValidString(sessionKey))
	{
		var async = require('async');
		async.waterfall([
			function(cb)
			{
				utils.checkManagerSession(sessionKey , cb);
			}
			,function(result , cb) 
			{
				// 실패 - 로그인 페이지 
				if(result == 0)
				{
					utils.notifyManagerSessionExpired(req , res);
				}
				// 성공 - 실제 작업코드.
				else
				{	
				/////////////////////////////////////////////////////////////////////////////////////////////
				
				/*
					Input parameters 

					articleCount
					page
					startPage
					endPage

					startDate 
					endDate 


				*/
					var articleCount = req.body.articleCount;

					var page = req.body.page;
					var startPage = req.body.startPage;
					var endPage = req.body.endPage;

					var startYear = req.body.startYear;		
					var startMonth = req.body.startMonth;		
					var startDay = req.body.startDay;		
					var startHour = req.body.startHour;		
					var startMin = req.body.startMin;		
					var startSec = req.body.startSec;		

					var endYear = req.body.endYear;		
					var endMonth = req.body.endMonth;		
					var endDay = req.body.endDay;		
					var endHour = req.body.endHour;		
					var endMin = req.body.endMin;		
					var endSec = req.body.endSec;		

					var blockCommentId = req.body.blockCommentId;
					var canceledReportId = req.body.canceledReportId;


					// 안넘어오면 오늘날짜 첨부터 끝까지 
					if(!utils.isValidString(startYear))
					{
						var today = new Date();

						startYear = '2015';
						startMonth = '01';
						startDay = '01';


						endYear = String(today.getFullYear());
						endMonth = utils.attachZero(today.getMonth()+1 , 2); //January is 0!
						endDay = utils.attachZero(today.getDate());

						startHour = startMin = startSec = '00';
						endHour ='23';
						endMin = endSec = '59';

					}

					var startDate = startYear+'-'+startMonth+'-'+startDay+' '+startHour+':'+startMin+':'+startSec;
					var endDate = endYear+'-'+endMonth+'-'+endDay+' '+endHour+':'+endMin+':'+endSec;


					if(!utils.isValidString(startDate))
						startDate = null;
					if(!utils.isValidString(endDate))
						endDate = null;


					utils.debug(req.originalUrl);

					//utils.callLog(req);
					if(!utils.isValid(articleCount) || articleCount <= 0)
						articleCount = 10;

					if(!utils.isValid(page) || page <=0 )
						page=1;
					else
						page = Number(page);

					if(!utils.isValid(startPage) || startPage <=0)
						startPage = 1; 
					else
						startPage = Number(startPage);

					if(!utils.isValid(endPage) || endPage <=0)
						endPage = 10;
					else
						endPage = Number(endPage);


					var fs = require('fs');
					fs.readFile('./template/reportedCommentList' , function(error,data)
					{
						if(error)
						{
							throw err;
						}
						var html = String(data);

						// 검색만 할 때 , 변경할 때 나눈다.
						var db = null;

						if(!utils.isValidString(blockCommentId))
							blockCommentId = null;
						if(!utils.isValidString(canceledReportId))
							canceledReportId = null;


						if(utils.isValidString(blockCommentId)|| utils.isValidString(canceledReportId))
						{
							db = global.master_db;
							console.log('master');
						}
						else
						{
							db = global.replica_db;
							console.log('replica');
						}

						db.connection.getConnection(function(err,connection)
						{
							if(err)
							{
								throw err;
							}

							var input_param = [articleCount, page, blockCommentId , canceledReportId , startDate, endDate, global.config.storage.download.url];

							var sql = 'call manage_getReportedCommentList(?,?,?,?,?,?,?)';

							var query = connection.query(sql, input_param , function (err, rows) 
							{
								connection.release();
								if(err)
								{
									throw err;
								}
								
								var totalCount = rows[0][0].totalCount;
								var totalPage = rows[0][0].totalPage;

								// 귀찮다 개수대로 때려넣자.
								fs.readFile('./template/reportedCommentItem' , function(error,data)
								{
									if(error)
									{
										throw err;
									}

									var totalItem = '';

									var thumbWidth=120;
									var videoWidth=427;

									for(i = 0 ; i < rows[1].length ; i++)
									{
										var item = String(data);
										item = item.split("%ARTICLE_ID%").join(rows[1][i].ARTICLEID);

										item = item.split("%REPORT_ID%").join(rows[1][i].REPORTID);
										
										if(!utils.isValidString(rows[1][i].MOVIEPATH))
											item = item.split("%MOVIE_PATH%").join('');
										else
											item = item.split("%MOVIE_PATH%").join(rows[1][i].MOVIEPATH);

										if(!utils.isValidString(rows[1][i].THUMBPATH))
											item = item.split("%THUMB_PATH%").join('');
										else
											item = item.split("%THUMB_PATH%").join(rows[1][i].THUMBPATH);

										item = item.split("%ENCRYPTED_ID%").join(rows[1][i].ENCRYPTEDARTICLEID);

										/// width , height 
										item = item.split("%THUMB_WIDTH%").join(thumbWidth); // thumbnail 가로는 고정 
										item = item.split("%THUMB_HEIGHT%").join(parseInt(thumbWidth*rows[1][i].HEIGHT/rows[1][i].WIDTH));

										item = item.split("%VIDEO_WIDTH%").join(videoWidth); // thumbnail 가로는 고정 
										item = item.split("%VIDEO_HEIGHT%").join(parseInt(videoWidth*rows[1][i].HEIGHT/rows[1][i].WIDTH));


										if(rows[1][i].BODY.length < 40)
										{
											for(l = rows[1][i].BODY.length;l<=40;l++)
												rows[1][i].BODY +='&nbsp;';
										}

										if(2 == rows[1][i].CONTENTSTATE)
											rows[1][i].BODY += '&nbsp;<font color=BLUE>PRIVATE</font>';
										else if(20 == rows[1][i].CONTENTSTATE)
											rows[1][i].BODY += '&nbsp;<font color=RED>DELETED</font>';

										if(rows[1][i].BODY.length < 50)
										{
											for(l = rows[1][i].BODY.length;l<=50;l++)
												rows[1][i].BODY +='&nbsp';
										}
										
										
										if(utils.isValidString(rows[1][i].BODY))
											item = item.split("%BODY%").join(rows[1][i].BODY);
										else
											item = item.split("%BODY%").join('');

										item = item.split("%REG_DATE%").join(rows[1][i].REGDATE);
										item = item.split("%VIEW_COUNT%").join(rows[1][i].VIEWCOUNT);
										item = item.split("%SHARE_COUNT%").join(rows[1][i].SHARECOUNT);
										item = item.split("%LIKE_COUNT%").join(rows[1][i].LIKECOUNT);
										item = item.split("%COMMENT_COUNT%").join(rows[1][i].COMMENTCOUNT);

										if(!utils.isValidString(rows[1][i].PROFILEPICPATH))
											item = item.split("%PROFILEPIC_PATH%").join(global.config.web.defaultProfileImageUrl);
										else
											item = item.split("%PROFILEPIC_PATH%").join(rows[1][i].PROFILEPICPATH);
										item = item.split("%NAME%").join(rows[1][i].NAME);
										item = item.split("%LOGIN_ID%").join(rows[1][i].LOGINID);

										item = item.split("%REPORT_DATE%").join(rows[1][i].REPORTDATE);
										/*
										switch(rows[1][i].REPORTTYPE)
										{
											case 1:
												item = item.split("%REPORT_TYPE%").join('음란/도박');	
												break;
											case 2:
												item = item.split("%REPORT_TYPE%").join('위험한내용');	
												break;
											case 3:
												item = item.split("%REPORT_TYPE%").join('스팸/사기');
												break;
											case 4:
												item = item.split("%REPORT_TYPE%").join('저작권침해');
												break;
											default:
												item = item.split("%REPORT_TYPE%").join('기타');	
										}
										*/
										switch(rows[1][i].REPORTTYPE)
										{
											case 1:
												item = item.split("%REPORT_TYPE%").join('obscene/illegal');	
												break;
											case 2:
												item = item.split("%REPORT_TYPE%").join('risky');	
												break;
											case 3:
												item = item.split("%REPORT_TYPE%").join('spam/scam');
												break;
											case 4:
												item = item.split("%REPORT_TYPE%").join('intellectual property violation');
												break;
											default:
												item = item.split("%REPORT_TYPE%").join('etc.');	
										}



										if(!utils.isValidString(rows[1][i].PROFILEPICPATH2))
											item = item.split("%PROFILEPIC_PATH2%").join(global.config.web.defaultProfileImageUrl);
										else
											item = item.split("%PROFILEPIC_PATH2%").join(rows[1][i].PROFILEPICPATH2);
										item = item.split("%NAME2%").join(rows[1][i].NAME2);
										item = item.split("%LOGIN_ID2%").join(rows[1][i].LOGINID2);


										item = item.split("%COMMENT_ID%").join(rows[1][i].COMMENTID);
										item = item.split("%COMMENT%").join(rows[1][i].COMMENT);
										if(!utils.isValidString(rows[1][i].PROFILEPICPATH3))
											item = item.split("%PROFILEPIC_PATH3%").join(global.config.web.defaultProfileImageUrl);
										else
											item = item.split("%PROFILEPIC_PATH3%").join(rows[1][i].PROFILEPICPATH3);
										item = item.split("%NAME3%").join(rows[1][i].NAME3);
										item = item.split("%LOGIN_ID3%").join(rows[1][i].LOGINID3);


										totalItem += '\n' + item;
									}

									html = html.split("%CONTENTS%").join(totalItem); // 내용
									
									html = html.split("%ARTICLE_COUNT%").join(articleCount); // 한 화면에 보이는 개수

									startDate = !startDate ? '' : startDate;						
									html = html.split("%START_DATE%").join(startDate); 

									endDate = !endDate ? '' : endDate;
									html = html.split("%END_DATE%").join(endDate); 


									var pageNumbers='';
									if(totalCount == 0)
									{
										page=0;
										html = html.split("%NEXT_DISABLED%").join('DISABLED'); 
										html = html.split("%PREV_DISABLED%").join('DISABLED'); 

									}
									else
									{
										if(page ==1 )
											html = html.split("%NEXT_DISABLED%").join('DISABLED'); 
										else
											html = html.split("%NEXT_DISABLED%").join(''); 

										if(page == totalPage)
											html = html.split("%PREV_DISABLED%").join('DISABLED'); 
										else
											html = html.split("%PREV_DISABLED%").join(''); 

										//페이지넘버리스트를 넘을 경우
										if(startPage > page)
										{
											// 최근10개 페이지 리스트
											endPage = page;
											startPage = page-9;
											// 앞으로 10개가 되지 않으면 뒤로 늘린다.
											if(startPage <= 0 )
											{
												startPage = 1;
												endPage = 10;
											}
										}
										else if(endPage < page)
										{
											// 다음 10개 페이지 리스트 
											startPage = page;
											endPage = startPage + 9;
											// 뒤로 10개가 되지 않으면 앞으로 늘린다.
											if(endPage > totalPage )
											{
												endPage = totalPage;
												startPage = endPage - 9;
											}
										}
										else
										{
											if(startPage <= 0 ) startPage = 1;
											if(endPage > totalPage) endPage = totalPage;
										}

										for(var i=startPage;i<=endPage;i++)
										{
											if(i == page)
												pageNumbers +='&nbsp;<font color=red>' + i + '</font>';
											else
												pageNumbers +='&nbsp;<a href=javascript:movePage(' + i + ')>' + i + '</a>';
										}
									}

									html = html.split("%CURRENT_PAGE%").join(page); 
									html = html.split("%START_PAGE%").join(startPage); 
									html = html.split("%END_PAGE%").join(endPage); 
									html = html.split("%TOTAL_PAGE%").join(totalPage); 
									html = html.split("%TOTAL_COUNT%").join(totalCount); 


									html = html.split("%PAGE_NUMBERS%").join(pageNumbers); 

									var strSelect = makeSelectYearString(Number(startYear));
									html = html.split("%START_YEAR%").join(strSelect); 
									strSelect = makeSelectMonthString(Number(startMonth));
									html = html.split("%START_MONTH%").join(strSelect); 
									strSelect = makeSelectDayString(Number(startDay));
									html = html.split("%START_DAY%").join(strSelect); 
									strSelect = makeSelectHourString(Number(startHour));
									html = html.split("%START_HOUR%").join(strSelect); 
									strSelect = makeSelectMinSecString(Number(startMin));
									html = html.split("%START_MIN%").join(strSelect); 
									strSelect = makeSelectMinSecString(Number(startSec));
									html = html.split("%START_SEC%").join(strSelect); 


									strSelect = makeSelectYearString(Number(endYear));
									html = html.split("%END_YEAR%").join(strSelect); 
									strSelect = makeSelectMonthString(Number(endMonth));
									html = html.split("%END_MONTH%").join(strSelect); 
									strSelect = makeSelectDayString(Number(endDay));
									html = html.split("%END_DAY%").join(strSelect); 
									strSelect = makeSelectHourString(Number(endHour));
									html = html.split("%END_HOUR%").join(strSelect); 
									strSelect = makeSelectMinSecString(Number(endMin));
									html = html.split("%END_MIN%").join(strSelect); 
									strSelect = makeSelectMinSecString(Number(endSec));
									html = html.split("%END_SEC%").join(strSelect); 



									res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
									res.end(html);

								}); // read file

							}); // query

						}); // getConnection

					}); // readfile
			//////////////////////////////////////////////////////////////////////////////////////////

				} // result==1 
			}
		]); //waterfall
	}
	// 암것도 없으면 loginPage
	else
	{
		utils.gotoManagerLoginPage(req , res);
	}

});

module.exports = router;